<template>
  <el-table-column
    :fixed="col.fixed === 'false' ? false : col.fixed"
    :sortable="col.sortable"
    :filters="col.filter ? filters(col) : undefined"
    :filter-method="col.filter ? filterHandler : undefined"
    v-if="col.show"
    show-overflow-tooltip
    :width="col.width"
    :label="col.label"
    :prop="col.prop"
    :align="col.align || 'center'"
  >
    <template v-if="!col.children || !col.children.length" slot-scope="scope">
      <i
        v-if="
          col.iconPosition === 'left' && parseIcon(col, scope.row[col.prop])
        "
        :class="parseIcon(col, scope.row[col.prop]).iconName"
        :style="`color:${parseIcon(col, scope.row[col.prop]).color}`"
      ></i>
      {{
        scope.row[col.prop] !== undefined
          ? scope.row[col.prop].value || scope.row[col.prop]
          : ''
      }}
      <i
        v-if="
          col.iconPosition === 'right' && parseIcon(col, scope.row[col.prop])
        "
        :class="parseIcon(col, scope.row[col.prop]).iconName"
        :style="`color:${parseIcon(col, scope.row[col.prop]).color}`"
      ></i>
    </template>
    <template v-if="col.children && col.children.length">
      <recurveColumn
        :commonTableData="commonTableData"
        v-for="(item, index) of col.children"
        :key="item.label + Math.random()"
        :col="item"
        :index="index"
      ></recurveColumn>
    </template>
  </el-table-column>
</template>

<script>
export default {
  name: 'recurveColumn',
  props: {
    col: {
      type: Object,
      default: () => {},
    },
    index: {
      type: Number,
    },
    commonTableData: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      color: {
        success: '#67C23A',
        warning: '#E6A23C',
        danger: '#F56C6C',
        info: '#909399',
      },
    }
  },
  methods: {
    parseIcon(col, oriData) {
      //data变量给下面eval(rule)里的rule里用
      let data = oriData.value === undefined ? oriData : oriData.value
      let noRule = true
      for (let status in col.icon) {
        let icon = col.icon[status]
        let rule = icon.rule
        let ruleArg = icon.ruleArg || ''
        if (!rule || rule === 'false') continue
        noRule = false
        rule = col.icon[status].rule
          .replace('{%%}', ruleArg)
          .replace(/\'/g, '"')
        let result = !!eval(rule)
        if (result) return icon
      }
      //前端匹配优先级高，如果前端没设置匹配规则，查看后端返回status字段状态
      if (noRule && oriData.status) {
        return col.icon[oriData.status]
      }
      return false
    },
    filters(col) {
      return Array.from(
        new Set(this.commonTableData.map((item) => item[col.prop]))
      ).map((item) => ({
        text: item,
        value: item,
      }))
    },
    filterHandler(value, row, column) {
      const property = column['property']
      return row[property] === value
    },
  },
}
</script>

<style scoped></style>
